package com.itheima.service.Impl;

import com.itheima.Utils.MapperUtil;
import com.itheima.domain.User;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class UserServiceImpl implements UserService {
    @Override
    public List<User> findAll() {
        List<User> userList=null;
        try {
            InputStream is = Resources.getResourceAsStream("sqlConfig.xml");
            SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
            SqlSession session = build.openSession();

            UserMapper mapper = session.getMapper(UserMapper.class);
             userList=mapper.findAll();

            session.commit();
            session.close();
            is.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return userList;
    }

    @Override
    public void save(User user) {

        SqlSession session = MapperUtil.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        mapper.save(user);

        MapperUtil.close(session);


    }

    @Override
    public void deleteByIds(Integer[] idsArray) {

        SqlSession session = MapperUtil.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        mapper.deleteByIds(idsArray);

        MapperUtil.close(session);



    }

    @Override
    public void update(User user) {
        SqlSession session = MapperUtil.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        mapper.update(user);

        MapperUtil.close(session);
    }


}
